package rui.example.spring.boot.mybatis.moreDatasource.configuraion;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ResourceLoader;

import javax.sql.DataSource;
import java.util.List;

@Configuration
@EnableConfigurationProperties({MybatisProperties.class})
public class MyBatisConfigurationSupport {

    @Bean(name = "masterDataSource")
    @Qualifier("masterDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "slaveDataSource")
    @Qualifier("slaveDataSource")
    @ConfigurationProperties(prefix="spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean
    public MybatisAutoConfiguration mybatisAutoConfiguration(MybatisProperties properties
            , ObjectProvider<Interceptor[]> interceptorsProvider, ResourceLoader resourceLoader
            , ObjectProvider<DatabaseIdProvider> databaseIdProvider
            , ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider) {

        return new MybatisAutoConfiguration(properties,interceptorsProvider,resourceLoader,databaseIdProvider
                ,configurationCustomizersProvider);
    }

}
